home *** CD-ROM | disk | FTP | other *** search
- Path: ceas.rochester.edu!usenet
- From: Lixin Pang <pang>
- Newsgroups: comp.lang.c
- Subject: Re: using MALLOC() w/ 2-d arrays
- Date: 28 Jan 1996 17:16:47 GMT
- Organization: University of Rochester School of Engineering and Applied Science
- Message-ID: <4egb20$c62@bilbo.ceas.rochester.edu>
- References: <4e9nm2$nna@cville-srv.wam.umd.edu> <3108F478.1831@cmt.lpr.mail.carel.fi>
- NNTP-Posting-Host: leonardo.me.rochester.edu
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.1N (X11; I; IRIX 5.3 IP22)
- X-URL: news:3108F478.1831@cmt.lpr.mail.carel.fi
-
- A dynamic 2D array can be obtained as following,
-
- --
-
- #include <stdio.h>
- #include <stdlib.h> /* for exit() */
-
- double** 2DArray = NULL;
-
- /* Pointer to "num_of_rows" pointers of double */
- 2DArray =(double**) malloc( num_of_rows * sizeof(double*) );
- if (!2DArray)
- {
- printf("Cannot allocate memory for 2d array!\n");
- exit(EXIT_FAILURE);
- }
-
- for (i=0; i<num_of_rows; i++)
- {
- /* Each 2DArray[i] is a pointer to "num_of_cols" doubles */
- 2DArray[i] = (double*) malloc( num_of_cols * sizeof(double) );
- if(!2DArray[i])
- {
- printf("Cannot allocate memory for 2d array!\n");
- exit(EXIT_FAILURE);
- }
- }
-
- Now 2DArray can be accessed as 2DArray[i][j]. You can specify
- num_of_rows and num_of_cols at run time.
-
- HTH,
-
- Lixin
- ____________________________________
- Department of Mechanical Engineering
- University of Rochester
- Rochester, NY 14627
- ____________________________________
-
-